/*
 * @Description: 路由接口的链接
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-09-24 12:15:53
 * @LastEditTime: 2021-10-03 17:51:12
 */
import Vue from 'vue'
import VueRouter from 'vue-router'

// ! 当把 Login 改为懒加载时，页面就会加载出错？？？
import Login from '@/components/Login.vue'
// import Home from '@/components/Home.vue'

// const Login = () => import(/* webpackChunkName: "group-start" */ '@/components/Login.vue')
const Home = () => import(/* webpackChunkName: "group-start" */ '@/components/Home.vue')

const Welcome = () => import(/* webpackChunkName: "group-start" */ '@/views/wlecome/Welcome.vue')
const Users = () => import(/* webpackChunkName: "group-user" */ '@/views/users/Users.vue')
const Rights = () => import(/* webpackChunkName: "group-right" */ '@/views/right/rights.vue')
const Roles = () => import(/* webpackChunkName: "group-right" */ '@/views/right/roles.vue')
const Cate = () => import(/* webpackChunkName: "group-goods" */ '@/views/goods/Cate.vue')
const GoodsParams = () => import(/* webpackChunkName: "group-goods" */ '@/views/goods/Params.vue')
const List = () => import(/* webpackChunkName: "group-goods" */ '@/views/goods/List.vue')
const Add = () => import(/* webpackChunkName: "group-oredr" */ '@/views/goods/Add.vue')
const Order = () => import(/* webpackChunkName: "group-order" */ '@/views/order/Order.vue')
const Stat = () => import(/* webpackChunkName: "group-data" */ '@/views/stat/Statistic.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: GoodsParams },
      { path: '/goods', component: List },
      { path: '/add', component: Add },
      { path: '/orders', component: Order },
      { path: '/reports', component: Stat }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') next()
  const token = window.sessionStorage.getItem('token')
  if (token) next()
  else next('/login')
})

// ! 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面
router.onError(error => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = router.history.pending.fullPath
  if (isChunkLoadFailed) {
    router.replace(targetPath)
  }
})
export default router
